package com.itheima.protocol.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.transaction.CuratorTransactionResult;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CuratorOperatorDemo {


    public static void main(String[] args) throws Exception {

        CuratorFramework curator = CuratorClientUtils.getInstance();
        System.out.println("连接成功...");

        /**
         * 创建节点
         */
        Stat stat = curator.checkExists().forPath("/curator");
        if (stat == null) {
            String result = curator.create().creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT)
                    .forPath("/curator/curator1/curator11", "123".getBytes());
            System.out.println(result);
        }


        /**
         * 获取数据
         */
        Stat stat1 = new Stat();
        byte[] bytes = curator.getData().storingStatIn(stat1).forPath("/curator");
        System.out.println(new String(bytes) + "---> stat: " + stat1);

        /**
         * 修改数据
         */
        Stat stat2 = curator.setData().forPath("/curator", "123".getBytes());
        if (stat2 != null) {
            System.out.println("更新成功");
        }

        /**
         * 异步操作
         */

        ExecutorService service = Executors.newFixedThreadPool(1);
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        curator.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).
                inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                        System.out.println(Thread.currentThread().getName() + "--> resultCode: " + event.getResultCode() + "-->" + event.getType());
                        countDownLatch.countDown();
                    }
                }, service).forPath("/mic", "123".getBytes());

        countDownLatch.await();
        service.shutdown();


        /**
         * 事务操作
         */

        Collection<CuratorTransactionResult> resultCollections = curator.inTransaction().create().forPath("/trans", "123".getBytes()).and().setData()
                .forPath("/curator", "2323".getBytes()).and().commit();
        for (CuratorTransactionResult result:resultCollections) {
            System.out.println(result.getForPath() + "--->" + result.getType());
        }

        /**
         * 删除节点
         */
        curator.delete().deletingChildrenIfNeeded().forPath("/curator");
        System.out.println("删除节点");


    }
}
